package com.example.mynote.ui.cloud;

import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.example.mynote.R;
import com.example.mynote.ui.MyDataViewModel;

import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.Bmob;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;

public class CloudFragment extends Fragment {

    private String TAG = "MainActivity";
    //登录窗口布局
    LinearLayout login;
    //登录按钮
    Button login_btn;
    //注销按钮
    Button logout_btn;
    //下载按钮
    ImageButton download_btn;
    //上传按钮
    ImageButton upload_btn;
    //云服务图标
    ImageView cloud_icon;
    //云服务说明文字
    TextView cloud_text;
    //底部云服务布局
    LinearLayout bottom;
    String username;
    String password;
    //当前登录状态
    Boolean ifLogin = false;
    //ViewModel声明
    private MyDataViewModel myDataViewModel;
    MutableLiveData<String> startDownload;
    MutableLiveData<String> startUpload;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {

        View root = inflater.inflate(R.layout.fragment_cloud, container, false);

        login_btn = (Button)root.findViewById(R.id.btn_login);
        logout_btn = (Button)root.findViewById(R.id.btn_logout);
        download_btn = (ImageButton) root.findViewById(R.id.btn_download);
        upload_btn = (ImageButton) root.findViewById(R.id.btn_upload);
        cloud_icon = (ImageView) root.findViewById(R.id.cloud_icon);
        cloud_text = (TextView) root.findViewById(R.id.cloud_text);
//        bottom = (LinearLayout) root.findViewById(R.id);

        myDataViewModel = new ViewModelProvider(getActivity()).get(MyDataViewModel.class);
        startDownload = (MutableLiveData<String>) myDataViewModel.getStartDownload();//开始下载
        startUpload = (MutableLiveData<String>) myDataViewModel.getStartUpload();//开始上传
        liveDataObserve();

        if(myDataViewModel.getIfLogin().getValue()==null){
            cloud_icon.setImageResource(R.drawable.ic_baseline_cloud_off_24);
            cloud_text.setText("您还未登录 登录即可使用云服务");
            login_btn.setVisibility(View.VISIBLE);
            logout_btn.setVisibility(View.INVISIBLE);
            download_btn.setVisibility(View.INVISIBLE);
            upload_btn.setVisibility(View.INVISIBLE);
        }else if(myDataViewModel.getIfLogin().getValue()==false){
            cloud_icon.setImageResource(R.drawable.ic_baseline_cloud_off_24);
            cloud_text.setText("您还未登录 登录即可使用云服务");
            login_btn.setVisibility(View.VISIBLE);
            logout_btn.setVisibility(View.INVISIBLE);
            download_btn.setVisibility(View.INVISIBLE);
            upload_btn.setVisibility(View.INVISIBLE);
        }else {
            cloud_icon.setImageResource(R.drawable.ic_baseline_cloud_done_24);
            cloud_text.setText("欢迎您用户"+username+",云服务已开启\n请在联网的环境下上传或同步本地数据");
            login_btn.setVisibility(View.INVISIBLE);
            logout_btn.setVisibility(View.VISIBLE);
            download_btn.setVisibility(View.VISIBLE);
            upload_btn.setVisibility(View.VISIBLE);
        }

        login_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                login();
            }
        });
        logout_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                logout();
            }
        });
        download_btn.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
//                LiveData<Boolean> start = myDataViewModel.getStartDownload();
                myDataViewModel.setStartDownload("start");
                Toast.makeText(getContext(), "开始云同步", Toast.LENGTH_SHORT).show();
                return true;
            }
        });
        upload_btn.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                myDataViewModel.setStartUpload("start");
                Toast.makeText(getContext(), "开始云同步", Toast.LENGTH_SHORT).show();
                return true;
            }
        });
//        MutableLiveData<Boolean> ifLogin = (MutableLiveData<Boolean>) myDataViewModel.getIfLogin();

        return root;
    }

    /**
     * 监听liveData
     */
    private void liveDataObserve(){
//        ifLogin.observe(getActivity(), new Observer<Boolean>() {
//            @Override
//            public void onChanged(Boolean b) {
//                Log.d(TAG, "用户登陆状态改变");
//            }
//        });
        //TODO:后续修改，便签和闹钟都同步完成时才将livedata改为“finish”
        startDownload.observe(getActivity(), new Observer<String>() {
            @Override
            public void onChanged(String b) {
                //TODO：会闪退
//                if(startDownload!=null && startDownload.getValue().equals("finish")) {
//                    Toast.makeText(getContext(), "云同步数据完成", Toast.LENGTH_SHORT).show();
//                    //设置下载标志为已完成
//                    myDataViewModel.setStartDownload("finished");
//                }
            }
        });
    }

//    @Override
//    public void onResume() {
//        super.onResume();
//        if(ifLogin==false){
//            cloud_icon.setImageResource(R.drawable.ic_baseline_cloud_off_24);
//            cloud_text.setText("您还未登录 登录即可使用云服务");
//            login_btn.setVisibility(View.VISIBLE);
//            logout_btn.setVisibility(View.INVISIBLE);
//            download_btn.setVisibility(View.INVISIBLE);
//            upload_btn.setVisibility(View.INVISIBLE);
//        }else {
//            cloud_icon.setImageResource(R.drawable.ic_baseline_cloud_done_24);
//            cloud_text.setText("欢迎您用户"+username+",云服务已开启\n请在联网的环境下上传或同步本地数据");
//            login_btn.setVisibility(View.INVISIBLE);
//            logout_btn.setVisibility(View.VISIBLE);
//            download_btn.setVisibility(View.VISIBLE);
//            upload_btn.setVisibility(View.VISIBLE);
//        }
//    }
//
//    @Override
//    public void onStart() {
//        super.onStart();
//        if(ifLogin==false){
//            cloud_icon.setImageResource(R.drawable.ic_baseline_cloud_off_24);
//            cloud_text.setText("您还未登录 登录即可使用云服务");
//            login_btn.setVisibility(View.VISIBLE);
//            logout_btn.setVisibility(View.INVISIBLE);
//            download_btn.setVisibility(View.INVISIBLE);
//            upload_btn.setVisibility(View.INVISIBLE);
//        }else {
//            cloud_icon.setImageResource(R.drawable.ic_baseline_cloud_done_24);
//            cloud_text.setText("欢迎您用户"+username+",云服务已开启\n请在联网的环境下上传或同步本地数据");
//            login_btn.setVisibility(View.INVISIBLE);
//            logout_btn.setVisibility(View.VISIBLE);
//            download_btn.setVisibility(View.VISIBLE);
//            upload_btn.setVisibility(View.VISIBLE);
//        }
//    }

    /**
     * Bmob数据库的user表Bean类
     */
    public class user{
        private String id;
        private String password;

        public void setId(String id) {
            this.id = id;
        }

        public String getId() {
            return id;
        }

        public String getPassword() {
            return password;
        }

        public void setPassword(String password) {
            this.password = password;
        }
    }

    /**
     * 尝试登陆，与登陆成功/失败后操作
     */
    private void login(){
        AlertDialog.Builder dialog = new AlertDialog.Builder(getContext());
        login = (LinearLayout)getLayoutInflater().inflate(R.layout.login_dialog,null);
        dialog.setTitle("用户登录").setMessage("请输入用户名和密码").setView(login);
        dialog.setPositiveButton("确定",new DialogInterface.OnClickListener(){
            @Override
            public void onClick(DialogInterface dialog,int which)
            {
                EditText userText = (EditText)login.findViewById(R.id.editText);
                EditText passwordText = (EditText)login.findViewById(R.id.paswdEdit);
                username=userText.getText().toString();
                password=passwordText.getText().toString();
                Bmob.initialize(getContext(),"72fa9d56a52f30cc685d026622b10f91");
                //查询记录
                BmobQuery<user> bmobQuery1 = new BmobQuery<user>();
                bmobQuery1.addWhereEqualTo("id", username);
                BmobQuery<user> bmobQuery2 = new BmobQuery<user>();
                bmobQuery2.addWhereEqualTo("password", password);
                List<BmobQuery<user>> andQuerys = new ArrayList<BmobQuery<user>>();
                andQuerys.add(bmobQuery1);
                andQuerys.add(bmobQuery2);
                BmobQuery<user> query = new BmobQuery<user>();
                query.and(andQuerys);
                query.findObjects(new FindListener<user>() {
                    @Override
                    public void done(List<user> Object, BmobException e) {
//                        if (e == null) {
//                            Log.d(TAG, "done: 查询成功:"+Object.size());
//                        } else {
//                            Log.d(TAG, "done: 查询失败"+e.getMessage()+","+e.getErrorCode());
//                        }
                        if (Object.size() == 1) {
                            //TODO:登录成功的一系列操作：
                            myDataViewModel.setIfLogin(true);
                            Toast.makeText(getContext(), "登陆成功", Toast.LENGTH_SHORT).show();
                            Log.d(TAG, "done: 查询成功:"+Object.size());
                            ifLogin=true;

                            myDataViewModel.setIfLogin(true);
                            cloud_icon.setImageResource(R.drawable.ic_baseline_cloud_done_24);
                            cloud_text.setText("欢迎您用户"+username+",云服务已开启\n请在联网的环境下上传或同步本地数据");
                            login_btn.setVisibility(View.INVISIBLE);
                            logout_btn.setVisibility(View.VISIBLE);
//                            bottom.setVisibility(View.VISIBLE);
                            download_btn.setVisibility(View.VISIBLE);
                            upload_btn.setVisibility(View.VISIBLE);

                        } else {
                            Toast.makeText(getContext(), "用户名或密码不正确！", Toast.LENGTH_SHORT).show();
                            Log.d(TAG, "done: 查询失败");
                        }
                    }
                });

                dialog.dismiss();
            }
        });
        dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });

        dialog.setIcon(R.drawable.ic_baseline_login_24);
        dialog.create();
        dialog.show();
    }

    /**
     * 退出登陆
     */
    private void logout(){
        Toast.makeText(getContext(), "退出账号成功", Toast.LENGTH_SHORT).show();
        myDataViewModel.setIfLogin(false);
        ifLogin=false;
        cloud_icon.setImageResource(R.drawable.ic_baseline_cloud_off_24);
        cloud_text.setText("您还未登录 登录即可使用云服务");
        login_btn.setVisibility(View.VISIBLE);
        logout_btn.setVisibility(View.INVISIBLE);
//        bottom.setVisibility(View.INVISIBLE);
        download_btn.setVisibility(View.INVISIBLE);
        upload_btn.setVisibility(View.INVISIBLE);
    }


}